package com.pxmeta.app.controller.community;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pxmeta.common.core.domain.AjaxResult;
import com.pxmeta.common.enums.DynamicEnum;
import com.pxmeta.common.utils.SecurityUtils;
import com.pxmeta.dynamic.entity.SearchHistory;
import com.pxmeta.dynamic.service.ISearchHistoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/community/search")
@RequiredArgsConstructor
@Api(tags = "搜索历史",value = "搜索历史")
public class SearchHistoryController {


    private final ISearchHistoryService searchHistoryService;


    @SaCheckLogin
    @GetMapping("/getSearchHistory")
    @ApiOperation("获取搜索历史")
    public AjaxResult<List<SearchHistory>> getSearchHistory(@RequestParam Long circleId){
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<SearchHistory> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SearchHistory::getUserId, userId)
                .eq(SearchHistory::getCircleId, circleId)
                .orderByDesc(SearchHistory::getUpdateTime);
        List<SearchHistory> list = searchHistoryService.list(wrapper);
        return AjaxResult.success(list);
    }

    @SaCheckLogin
    @DeleteMapping("/cleanHistory")
    @ApiOperation("清空搜索历史")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "circleId", value = "圈子id"),
                    @ApiImplicitParam(name = "type", value = "0全部，1动态，2话题"),
            }
    )
    public AjaxResult<List<SearchHistory> > cleanHistory(@RequestParam Long circleId, @RequestParam Integer type){

        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<SearchHistory> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SearchHistory::getUserId, userId)
                .eq(SearchHistory::getCircleId, circleId);
        if (type != null && type != 0){
           wrapper.eq(SearchHistory::getType, type);
        }
        List<SearchHistory> list = searchHistoryService.list(wrapper);
        if (CollectionUtil.isNotEmpty(list)){
            searchHistoryService.removeBatchByIds(list.stream().map(SearchHistory::getId).collect(Collectors.toList()));
        }
        return AjaxResult.success();
    }


}
